package com.comtop.topcloud.device.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.comtop.topcloud.device.mapper.EnergySystemAlarmLibraryMapper;
import com.comtop.topcloud.device.model.AlarmConfig;
import com.comtop.topcloud.device.model.mysql.EnergySystemAlarmLibrary;
import com.comtop.topcloud.device.service.EnergySystemAlarmLibraryService;
import com.comtop.topcloud.device.util.StringUtils;
import org.redisson.api.RMapCache;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class EnergySystemAlarmLibraryServiceImpl extends ServiceImpl<EnergySystemAlarmLibraryMapper, EnergySystemAlarmLibrary> implements EnergySystemAlarmLibraryService {


    public static final String ALARM_CONFIG_KEY = "ALARM_CONFIG_KEY";

    @Resource
    private RedissonClient redisson;

    public List<AlarmConfig> getAlarmConfigByDeviceTypeAndTerminalType(String deviceType, Integer terminalType) {
        RMapCache<String, List<AlarmConfig>> configRMapCache = redisson.getMapCache(ALARM_CONFIG_KEY);
        String key = StringUtils.generateRedisKey(deviceType, String.valueOf(terminalType));
        List<AlarmConfig> alarmConfigs = configRMapCache.get(key);

        // 如果缓存中有数据，直接返回
        if (!CollectionUtils.isEmpty(alarmConfigs)) {
            return alarmConfigs;
        }

        alarmConfigs = baseMapper.getAlarmConfigByDeviceTypeAndTerminalType(deviceType, terminalType);
        if (CollectionUtils.isEmpty(alarmConfigs)) {
            AlarmConfig defaultAlarmConfig = new AlarmConfig();
            alarmConfigs = new ArrayList<>();
            alarmConfigs.add(defaultAlarmConfig);  // 将默认对象添加到列表
            configRMapCache.put(key, alarmConfigs, 30, TimeUnit.MINUTES);  // 设置缓存过期时间
        } else {
            // 数据库有数据，存储到缓存中
            configRMapCache.put(key, alarmConfigs, 30, TimeUnit.MINUTES);
        }

        return alarmConfigs;
    }


}
